package com.etc;

import com.google.common.base.Optional;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.streaming.Durations;
import org.apache.spark.streaming.Time;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairDStream;
import org.apache.spark.streaming.api.java.JavaReceiverInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import scala.Tuple2;

import java.sql.Connection;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @Auther: Wangcc
 * @Date: 2018/8/29 10:29
 * @Description:  基于持久化机制的实时wordcount程序
 */
public class PersistWordCount {
    public static void main(String[] args) {
        SparkConf conf = new SparkConf()
                .setMaster("local[2]")
                .setAppName("KafkaWordCount");

        JavaStreamingContext jssc = new JavaStreamingContext(conf, Durations.seconds(5));

        jssc.checkpoint("hdfs://spark1:9000/wordcount_checkpoint");
        JavaReceiverInputDStream<String> lines = jssc.socketTextStream("192.168.33.191", 9999);


        JavaDStream<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public Iterable<String> call(String s) throws Exception {
                return Arrays.asList(s.split(" "));
            }
        });


        JavaPairDStream<String, Integer> pairs = words.mapToPair(

                new PairFunction<String, String, Integer>() {

                    private static final long serialVersionUID = 1L;

                    @Override
                    public Tuple2<String, Integer> call(String word)
                            throws Exception {
                        return new Tuple2<String, Integer>(word, 1);
                    }

                });

        JavaPairDStream<String, Integer> wordCounts = pairs.updateStateByKey(new Function2<List<Integer>, Optional<Integer>, Optional<Integer>>() {
            @Override
            public Optional<Integer> call(List<Integer> integers, Optional<Integer> integerOptional) throws Exception {
                int newcount = 0;
                if (integerOptional.isPresent()){
                    newcount += integerOptional.get();
                }
                for (Integer integer : integers) {
                    newcount += integer;
                }
                return Optional.of(newcount);
            }
        });


        // 每次得到当前所有单词的统计次数之后，将其写入mysql存储，进行持久化，以便于后续的J2EE应用程序
        // 进行显示
        wordCounts.foreach(new Function2<JavaPairRDD<String, Integer>, Time, Void>() {

            private static final long serialVersionUID = 1L;

            @Override
            public Void call(JavaPairRDD<String, Integer> wordCountsRDD, Time time) throws Exception {

                wordCountsRDD.foreachPartition(new VoidFunction<Iterator<Tuple2<String, Integer>>>() {
                    @Override
                    public void call(Iterator<Tuple2<String, Integer>> tuple2Iterator) throws Exception {
                        // 给每个partition，获取一个连接
                        Connection conn = ConnectionPool.getConnection();

                        // 遍历partition中的数据，使用一个连接，插入数据库
                        Tuple2<String, Integer> wordCount = null;
                        while(tuple2Iterator.hasNext()) {
                            wordCount = tuple2Iterator.next();
                            String sql = "insert into wordcount(word,count) "
                                    + "values('" + wordCount._1 + "'," + wordCount._2 + ")";

                            Statement stmt = conn.createStatement();
                            stmt.executeUpdate(sql);
                        }
                        ConnectionPool.returnConnection(conn);
                    }
                });
                return null;
            }
        });

        jssc.start();
        jssc.awaitTermination();
        jssc.stop();

    }
}
